package com.wx.mall.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.wx.mall.common.api.CommonPage;
import com.wx.mall.common.api.PageVo;
import com.wx.mall.common.exceptions.ApiException;
import com.wx.mall.common.utils.UploadUtil;
import com.wx.mall.common.vo.goods.SpuVo;
import com.wx.mall.goods.entity.*;
import com.wx.mall.goods.mapper.SpuMapper;
import com.wx.mall.goods.service.IBrandService;
import com.wx.mall.goods.service.ICategoryService;
import com.wx.mall.goods.service.ISpuService;
import com.wx.mall.goods.vo.req.SpuMatchVo;
import com.wx.mall.goods.vo.resp.DicountVo;
import com.wx.mall.goods.vo.resp.SpuCountVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ljl
 * @since 2020-04-17
 */
@Service
public class SpuServiceImpl extends ServiceImpl<SpuMapper, Spu> implements ISpuService {
    /**
     * 文件上传路径
     */
    @Value("${localhost.file.path}")
    private String filePath;
    @Autowired
    private UploadUtil uploadUtil;
    @Autowired
    private IBrandService brandService;

    @Autowired
    private ICategoryService service;


    @Override
    public  DicountVo getSpuByCategoryId(String categoryId) {

        //获取到分类的数据
        List<Category> categoryAll = service.getCategoryAll();
        DicountVo vo=new DicountVo();
        QueryWrapper<Spu> wrapper=new QueryWrapper<>();
        wrapper.like("category_id",categoryId);
        List<Spu> spu=this.list(wrapper);
        List<Integer> idList=new ArrayList<>();

        for (Spu sp:spu
        ) {
            idList.add(sp.getId());
        };

        vo.setIds(idList);

        String name="";
        String[] ids=categoryId.split(";");
        for (String id:ids
        ) {
            Integer caId=Integer.valueOf(id);

            for (Category cate: categoryAll
            ) {
                if(cate.getCategoryId()==caId){

                    name+=cate.getCategoryName()+',';
                }
            }

        };

        vo.setCategoryName(name);


        return vo;
    }

    @Override
    public List<Spu> getByName(String name) {
        QueryWrapper<Spu> wrapper=new QueryWrapper<>();
        wrapper.like("name",name);

        List<Spu> list=this.list(wrapper);

        return list;
    }

    @Override
    public Spu getByNameT(String name) {
        QueryWrapper<Spu> wrapper=new QueryWrapper<>();
        wrapper.eq("name",name);

        Spu spu=this.getOne(wrapper);

        return spu;
    }

    @Override
    public CommonPage<SpuVo> pageList(PageVo vo) {
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());

        List<SpuVo> list = new ArrayList<>();
        for (Spu spu : this.list()) {
            list.add(parseSpu(spu));
        }

        return CommonPage.restPage(list);
    }

    @Override
    public SpuCountVo countSpu() {
        SpuCountVo vo = new SpuCountVo();
        vo.setTotal(this.count());
        vo.setSale(this.count(new QueryWrapper<Spu>().eq("is_marketable", 1)));
        vo.setSold(this.count(new QueryWrapper<Spu>().eq("is_marketable", 0)));
        vo.setVerified(this.count(new QueryWrapper<Spu>().eq("status", 2)));
        vo.setInReview(this.count(new QueryWrapper<Spu>().eq("status", 1)));
        vo.setAudit(this.count(new QueryWrapper<Spu>().eq("status", 0)));

        return vo;
    }

    @Override
    public CommonPage<SpuVo> pageMatch(SpuMatchVo vo) {
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        QueryWrapper<Spu> wrapper = new QueryWrapper<>();
        getMatchWrapper(wrapper,vo).like("encode", vo.getNameOrEncode());
        wrapper.or();
        getMatchWrapper(wrapper,vo).like("name", vo.getNameOrEncode());

        CommonPage<Spu> spuPage = CommonPage.restPage(this.list(wrapper));
        List<SpuVo> list = new ArrayList<>();
        for (Spu spu : spuPage.getList()) {
            SpuVo spuVo = parseSpu(spu);

            list.add(spuVo);
        }
        CommonPage<SpuVo> page = CommonPage.restPage(list);
        page.setTotalPage(spuPage.getTotalPage());
        page.setTotal(spuPage.getTotal());
        page.setPageSize(spuPage.getPageSize());
        page.setPageNum(spuPage.getPageNum());
        return page;
    }

    @Override
    public CommonPage<SpuVo> pageMatchRecycle(SpuMatchVo vo) {
//获取到分类的数据
        List<Category> categoryAll = service.getCategoryAll();
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        QueryWrapper<Spu> wrapper = new QueryWrapper<>();
        getMatchWrapper(wrapper,vo).like("encode", vo.getNameOrEncode());
        wrapper.or();
        getMatchWrapper(wrapper,vo).like("name", vo.getNameOrEncode());

        CommonPage<Spu> spuPage = CommonPage.restPage(this.list(wrapper));
        List<SpuVo> list = new ArrayList<>();
        for (Spu spu : spuPage.getList()) {
            SpuVo spuVo = parseSpu(spu);
//            将分类id转化成拼接的分类名
            String[] cateList=spuVo.getCategoryId().split(";");
//            暂时存储获取的分类

            String name="";

            for (String cate:cateList
            ) {
//                将分类表循环
                for (Category category:categoryAll
                ) {
                    Integer id=Integer.valueOf(cate);

                    if( category.getCategoryId()==id) {
                        name+=category.getCategoryName()+',';

                    }

                }


            };

//            将获取到的值进行赋值
            spuVo.setCategoryId(name);


            list.add(spuVo);
        }
        CommonPage<SpuVo> page = CommonPage.restPage(list);
        page.setTotalPage(spuPage.getTotalPage());
        page.setTotal(spuPage.getTotal());
        page.setPageSize(spuPage.getPageSize());
        page.setPageNum(spuPage.getPageNum());
        return page;
    }

    @Override
    public Integer insertEntity(SpuVo vo) {
        QueryWrapper<Spu> wrapper = new QueryWrapper<>();
        wrapper.eq("encode", vo.getEncode());
        wrapper.or().eq("name", vo.getName());
        Spu spu = new Spu();
        //将Spu实体中的数据复制到SpuVo中
        BeanUtils.copyProperties(vo, spu);
        if (this.getOne(wrapper) == null) {
            boolean save = this.save(spu);
            if (!save) {
                throw new ApiException("添加商品SPU失败。");
            }
        } else {
            boolean update = this.update(spu, wrapper);
            if (!update) {
                throw new ApiException("修改商品SPU失败。");
            }
        }

        return selectOneByEncode(vo).getId();
    }

    @Override
    public void deleteEntity(Integer id) {
        Spu spu = new Spu();
        spu.setId(id);
        spu.setIsMarketable(0);
        spu.setIsDelete(1);

        boolean remove = this.updateById(spu);
        if (!remove) {
            throw new ApiException("删除商品SPU失败。");
        }
    }

    @Override
    public SpuVo selectEntity(Integer id) {
        return parseSpu(this.getById(id));
    }

    @Override
    public SpuVo selectOneByEncode(SpuVo vo) {
        QueryWrapper<Spu> wrapper = new QueryWrapper<>();
        // 按商品货号查询
        wrapper.eq("encode", vo.getEncode());

        return parseSpu(this.getOne(wrapper));
    }

    @Override
    public void updateEntity(SpuVo vo) {
        Spu spu = parseSpuVo(vo);

        boolean update = this.updateById(spu);
        if (!update) {
            throw new ApiException("更新商品SPU失败。");
        }
    }

    @Override
    public Map<String, String> uploadImage(MultipartFile file, String name) {
        return uploadUtil.uploadUUID(file, filePath, name);
    }

    @Override
    public Boolean deleteImage(String fileName) {
        return uploadUtil.remove(filePath, fileName, UploadUtil.Encode.UUID);
    }

    private QueryWrapper<Spu> getMatchWrapper(QueryWrapper<Spu> wrapper,SpuMatchVo vo){
        // 按条件查询
        if(vo.getBrand() != null){
            wrapper.eq("brand_id", vo.getBrand());
        }
        if(vo.getAudit() != null){
            wrapper.eq("status", vo.getAudit());
        }
        if(vo.getSold() != null){
            wrapper.eq("is_marketable", vo.getSold());
        }
        if(vo.getAvailable() != null){
            wrapper.eq("is_delete", vo.getAvailable());
        }
        wrapper.like("category_id", vo.getCategory());
        switch (vo.getSort()){
            case 0:
                wrapper.orderByAsc("id");
                break;
            case 1:
                wrapper.orderByAsc("name");
                break;
            case 2:
                wrapper.orderByAsc("encode");
                break;
            case 3:
                wrapper.orderByDesc("is_marketable");
                break;
            case 4:
                wrapper.orderByDesc("sale");
                break;
            case 5:
                wrapper.orderByDesc("status");
                break;
            case 6:
                wrapper.orderByAsc("is_delete");
                break;
        }
        return wrapper;
    }

    private SpuVo parseSpu(Spu spu){
        SpuVo spuVo = new SpuVo();
        //将Spu实体中的数据复制到SpuVo中
        BeanUtils.copyProperties(spu, spuVo);
        spuVo.setBrandName(brandService.getById(spu.getBrandId()).getName());
        switch (spu.getIsDelete()) {
            case 0:
                spuVo.setDelLabel("正常");
                break;
            case 1:
                spuVo.setDelLabel("已删除");
                break;
            default:
                break;
        }
        switch (spu.getStatus()) {
            case 0:
                spuVo.setStaLabel("待审核");
                break;
            case 1:
                spuVo.setStaLabel("未通过");
                break;
            case 2:
                spuVo.setStaLabel("已审核");
                break;
            default:
                break;
        }
        spuVo.setMarketable(spu.getIsMarketable() == 1);
        return spuVo;
    }

    private Spu parseSpuVo(SpuVo spuVo){
        Spu spu = new Spu();
        //将Spu实体中的数据复制到SpuVo中
        BeanUtils.copyProperties(spuVo, spu);
        // 布尔类型 如果为空 设置布尔值为空类型时 会报错  需要排除它
        if (spuVo.getMarketable() != null){
            spu.setIsMarketable(spuVo.getMarketable() ? 1 : 0);
        }
        return spu;
    }

}
